// src/initialization/initialization.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { createHash } from 'crypto';
import { encodePwd } from 'src/utils';

const salt = 'cvnert'; // 拼接随机数防破解

@Injectable()
export class InitializationService implements OnModuleInit {
  constructor(private readonly prisma: PrismaService) {}

  async onModuleInit() {
    await this.initializeAdminRole();
    await this.initRouter();
  }

  async initializeAdminRole() {
    try {
      const adminExists = await this.prisma.admin.count({
        where: { userName: 'admin' },
      });

      if (adminExists > 0) {
        console.log('管理员账户已存在，跳过初始化');
        return;
      }

      const hashedPassword = await encodePwd('admin');

      await this.prisma.admin.create({
        data: {
          userName: 'admin',
          password: hashedPassword,
          avatar:
            'https://miaobi-lite.bj.bcebos.com/miaobi/5mao/b%276Jyh56yU5bCP5paw5oOF5L6j5aS05YOPXzE3Mjg5NDgyODguMjQ1MjcyMg%3D%3D%27/0.png',
        },
      });

      console.log('管理员账户初始化成功');
    } catch (error) {
      console.error('初始化管理员账户失败:', error);
      throw error; // 让 NestJS 处理错误并可能终止应用
    }
  }

  async initRouter() {
    try {
      const routerNum = await this.prisma.router.count({
        where: {
          permission: 'all',
        },
      });
      if (routerNum > 0) {
        console.log('路由已存在，跳过初始化');
        return;
      }

      await this.prisma.router.createMany({
        data: [
          {
            name: '首页',
            path: '/dashboard',
            icon: 'PlusCircleOutlined',
            component: 'Dashboard',
            permission: 'all',
          },
          {
            name: '首页',
            path: '/dashboard',
            icon: 'PlusCircleOutlined',
            component: 'Dashboard',
            permission: 'all',
          },
          {
            name: '首页',
            path: '/dashboard',
            icon: 'PlusCircleOutlined',
            component: 'Dashboard',
            permission: 'all',
          },
        ],
      });

      console.log('路由初始化成功');
    } catch (error) {
      console.error('初始化路由失败:', error);
      throw error; // 让 NestJS 处理错误并可能终止应用
    }
  }
}
